package com.onpositive.data.serializer.writers;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import com.onpositive.data.serializer.readers.DefaultReaderFactory;
import com.onpositive.data.serializer.writers.AbstractWriter;

public class ByteArrayWriter extends AbstractWriter<byte[]> {
	
	private ArrayList<Integer> offsets ;
	
	private ByteArrayOutputStream streamMain ;
	
	public ByteArrayWriter() {
		super( byte[].class );
		
		this.offsets = new ArrayList<Integer>() ;
		this.offsets.add(0);
		
		this.streamMain = new ByteArrayOutputStream() ;		
	}

	@Override
	public void append( byte[] value )
	{
		int lastOffset = offsets.get( offsets.size()-1 ) ;
		if( value != null && value.length != 0 )
		{
			lastOffset += value.length ;
			try {
				streamMain.write( value ) ;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}				
		offsets.add( lastOffset ) ;
	}

	@Override
	protected void doSerialize()
	{
		Integer totalSizeInBytes = offsets.get( offsets.size()-1 );
		
		super.writeIntToStream( totalSizeInBytes ) ;
		super.writeIntToStream( offsets.size() ) ;
		
		int dataOffset = super.getDataOffset() + INT_SIZE * offsets.size()  ;
		
		for( Integer i : offsets )
			super.writeIntToStream( i + dataOffset ) ;
	
		byte[] bArr = streamMain.toByteArray() ;
		super.writeByteArrayToStream( bArr ) ;		
	}

	@Override
	protected int getID()
	{
		return DefaultReaderFactory.RW_ID_BYTE_ARRAY ;		
	}

	public int getSize() {
		return streamMain.size() + INT_SIZE * offsets.size();
	}
}
